package info

import (
	"context"
	"devops/src/common"
	"devops/src/models"
	"devops/src/modules/agent/rpc"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/log/level"
)

func TickerInfoCollectAndReport(cli *rpc.RpcCli, ctx context.Context, logger log.Logger) error {
	ticker := time.NewTicker(5 * time.Second)

	level.Info(logger).Log("msg", "TickerInfoCollectAndReport.start")
	CollectBaseInfo(cli, logger)
	defer ticker.Stop()
	for {
		select {
		case <-ctx.Done():
			level.Info(logger).Log("msg", "receive_quit_signal_and_quit")
			return nil
		case <-ticker.C:
			CollectBaseInfo(cli, logger)
		}
	}
}

func CollectBaseInfo(cli *rpc.RpcCli, logger log.Logger) {
	// 收集基础信息
	var sn string
	var err error
	var cpu string
	var mem string
	var disk string
	//反引号
	snShellCloud := `curl -s http://169.254.169.254/a/meta-data/instance/id`
	snShellHost := ` dmidecode  -s system-serial-number|tail -n 1|tr -d '\n'`
	cpuShell := `cat /proc/cpuinfo | grep processor | wc -l|tr -d '\n'`
	memShell := `cat /proc/meminfo | grep MemTotal | awk '{printf "%d",$2/1024/1024}'`
	diskShell := `df -h | grep '/dev'|grep -v '/var/lib'|grep  -v tmpfs|awk '{sum += $2};END{printf "%d",sum/1024/1024}'`
	sn, err = common.ShellCommand(snShellCloud)
	if err != nil || sn == "" {
		sn, err = common.ShellCommand(snShellHost)
	}
	level.Info(logger).Log("msg", "collect base info", "sn", sn)

	cpu, err = common.ShellCommand(cpuShell)
	if err != nil {
		level.Error(logger).Log("msg", "collect cpu info error", "error", err)
	}
	level.Info(logger).Log("msg", "collect base info", "cpu", cpu)
	mem, err = common.ShellCommand(memShell)
	if err != nil {
		level.Error(logger).Log("msg", "collect mem info error", "error", err)
	}
	level.Info(logger).Log("msg", "collect base info", "mem", mem)
	disk, err = common.ShellCommand(diskShell)
	if err != nil {
		level.Error(logger).Log("msg", "collect disk info error", "error", err)
	}
	level.Info(logger).Log("msg", "collect base info", "disk", disk)
	ipAddr := common.GetLocalIP()
	hostName := common.GetHostName()

	//common 里放一个shell 连接执行函数，放置获取ip和hostname的，这里放置的是调用shell 传入的函数
	//models/resource_host.go 放的是一个结构体。这里进行实例
	hostobj := models.AgentCollectInfo{CPU: cpu, Disk: disk, HostName: hostName, IpAddr: ipAddr, Mem: mem, SN: sn}
	cli.HostInfoReport(hostobj)
}
